package me.fenglu.flowable.controller;

import me.fenglu.flowable.bean.MyTask;
import me.fenglu.flowable.service.MyTaskService;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.image.impl.DefaultProcessDiagramGenerator;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/task")
public class TaskController {
    
    @Autowired
    private MyTaskService myTaskService;
    
    @PostMapping(value = "/process/{processKey}")
    public Map<String, Object> startProcessInstance(@PathVariable String processKey, @RequestBody Map<String, Object> variables) {
        //使用Flowbale API初始化一个流程
        myTaskService.startProcess(processKey, variables);
        Map<String, Object> ret = new HashMap<>();
        ret.put("resCode", "200");
        ret.put("message", "您的请假审批流程已启动，请耐心等待审批吧！");
        return ret;
    }
    
    @PostMapping(value = "/tasks/{type}/{assignee}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public List<MyTask> getTasks(@PathVariable String assignee, @PathVariable String type) {
        System.out.println(assignee + "----" + type);
        List<MyTask> taskList = myTaskService.getTasks(assignee, type);
        return taskList;
    }
    
    @PostMapping(value = "/approve/{taskId}")
    public Map<String, Object> approve(@PathVariable String taskId, HttpServletRequest request, @RequestBody Map<String, Object> params) {
        boolean approved = params.get("approved").toString().equalsIgnoreCase("Y");
        myTaskService.complete(taskId, approved);
        Map<String, Object> ret = new HashMap<>();
        ret.put("resCode", "200");
        ret.put("message", "请假审批完成");
        return ret;
    }
    
    @PostMapping(value = "/history/{type}/{assignee}")
    public List<MyTask> history(@PathVariable String assignee, @PathVariable String type) {
        List<MyTask> taskList = myTaskService.getHistoryTasks(assignee, type);
        return taskList;
    }
    
    @GetMapping(value = "/img/{processInstanceId}")
    public void img(@PathVariable String processInstanceId, HttpServletResponse resp) throws Exception {
        HistoricProcessInstance historicProcessInstance = myTaskService.getHisPI(processInstanceId);
        List<String> highLightedActivities = new ArrayList<>();
        if (historicProcessInstance.getEndActivityId() != null) {
                highLightedActivities.add(historicProcessInstance.getEndActivityId());
        }else {
            HistoricTaskInstance historicTaskInstance = myTaskService.getHistoricTaskInstance(processInstanceId);
            highLightedActivities = myTaskService.getActiveActivityIds(historicTaskInstance.getExecutionId());
        }
	    
     
	    BpmnModel bpmnModel = myTaskService.getBpmnModel(historicProcessInstance.getProcessDefinitionId());
	    DefaultProcessDiagramGenerator diagramGenerator = new DefaultProcessDiagramGenerator();
	    List<String> highLightedFlows = new ArrayList<>();
	    InputStream in = diagramGenerator.generateDiagram(bpmnModel, "png", highLightedActivities, highLightedFlows, "宋体", "宋体", "宋体", null, 1.0, true);
	
	    byte data[] = readInputStream(in);
	    ServletOutputStream os = resp.getOutputStream();
	    os.write(data);
	    os.flush();
    }
	
	public byte[] readInputStream(InputStream inStream) throws Exception{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[2048];
		int len = 0;
		while( (len=inStream.read(buffer)) != -1 ){
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		return outStream.toByteArray();
	}
}
